//
//  PPNetRequest.m
//  PPNetworking
//
//  Created by 邓标祥 on 2020/12/15.
//

#import "PPNetRequest.h"

@implementation PPNetRequest

+ (instancetype)request {
    return [[[self class] alloc] init];
}

- (instancetype)init {
    if (self = [super init]) {
        _key = @"";
        _requestType = PPNetRequest_normal;
        _httpMethod = PPNetHTTPMethod_POST;
        _requestSerializerType = PPNetRequestSerializer_raw;
        _responseSerializerType = PPNetResponseSerializer_json;
        _timeoutInterval = 20.0;
        
        _useGeneralServer = NO;
        _useGeneralHeaders = NO;
        _useGeneralParameters = NO;
        _isAnalyticData = NO;
    }
    return self;
}

- (void)cleanCallbackBlocks {
    _successBlock = nil;
    _failureBlock = nil;
    _finishedBlock = nil;
}

- (void)classModelWithResponseObject:(id)responseObject onResultBlock:(PPNetJsonResultBlock)resultBlock{
    
}

/// 添加Header
- (void)addHeader:(NSDictionary<NSString *, NSString *> *)headers {
    
    NSMutableDictionary<NSString *, NSString *> *tempHeader = [[NSMutableDictionary alloc] init];
    if (self.headers && headers) {
        [tempHeader addEntriesFromDictionary:self.headers];
        [tempHeader addEntriesFromDictionary:headers];
        self.headers = tempHeader;
    }
}

@end

/// ************************************ 全省港澳所有既分割线唯独呢条至靓仔 ************************************ ///

#import "PPNetError.h"
@interface PPNetBatchRequest () {
    dispatch_semaphore_t _lock;
}


@property (nonatomic, strong) NSMutableArray *requestArray;
@property (nonatomic, assign) NSInteger finishedCount;
@property (nonatomic, copy) PPBCFinishedBlock finishedBlock;

@end

@implementation PPNetBatchRequest

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    _finishedCount = 0;
    _lock = dispatch_semaphore_create(1);

    _requestArray = [NSMutableArray array];
    _responseDict = [NSMutableDictionary dictionary];
    _errorDict = [NSMutableDictionary dictionary];
    return self;
}

- (void)addRequest:(PPNetRequest *)request{
    if (request) {
        [_requestArray addObject:request];
    }
}

- (void)addRequestArray:(NSArray<PPNetRequest *> *)array{
    if (array && array.count) {
        [_requestArray addObjectsFromArray:array];
    }
}


- (BOOL)onFinishedOneRequest:(PPNetRequest *)request
                    response:(id)responseObject
                       error:(NSError *)error {
    BOOL isFinished = NO;
    /// 安全起见加个线层锁
    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
    
    if (responseObject) {
        
        if (request.isAnalyticData) {
            
            __weak __typeof__(self)weakSelf = self;
            
//            @PPWeakObj(self);
            [request classModelWithResponseObject:responseObject onResultBlock:^(id  _Nullable resultObject, PPNetError * _Nullable resultError) {
                __strong __typeof__(weakSelf) strongSelf = weakSelf;
//                @PPStrongObj(self);
                if (resultError) {
                    strongSelf.errorDict[request.key] = resultError;
                }else{
                    strongSelf.responseDict[request.key] = resultObject;
                }
            }];
        }else {
            _responseDict[request.key] = responseObject;
        }
    }else{
        if (error) {
            PPNetError *ppError = [PPNetError errorWithSystemError:error];
            _errorDict[request.key] = ppError;
        }else {
            _errorDict[request.key] = [PPNetError errorWithCode:PPNetError_emptyData];
        }
    }
    _finishedCount++;
    if (_finishedCount == _requestArray.count) {
        PPNetBatchResult *result = [[PPNetBatchResult alloc]init];
        result.responseDict = _responseDict;
        result.errorDict = _errorDict;
        
        !_finishedBlock?:_finishedBlock(result);
        [self cleanCallbackBlocks];
        isFinished = YES;
    }
    dispatch_semaphore_signal(_lock);
    return isFinished;
}

- (void)cleanCallbackBlocks{
    _finishedBlock = nil;
}

@end


/// ************************************ 全省港澳所有既分割线唯独呢条至靓仔 ************************************ ///


@implementation PPNetBatchResult

- (instancetype)init{
    if (self = [super init]) {
        _responseDict = [[NSMutableDictionary alloc]init];
        _errorDict = [[NSMutableDictionary alloc]init];
    }
    return self;
}

- (_Nullable id)resultForKey:(NSString *)key{
    
    id response = [_responseDict valueForKey:key];
    if (response) {
        return response;
    }
    return nil;
}

- (PPNetError *)errorResultForKey:(NSString *)key{
    
    PPNetError *error = [_errorDict valueForKey:key];
    if (error) {
        return error;
    }else{
        return [PPNetError errorWithCode:PPNetError_emptyData];
    }
}

@end
